package alert

import (
	"bytes"
	"encoding/json"
	"errors"
	"github.com/tidwall/gjson"
	"io/ioutil"
	"net/http"
	"vrcm/src/vrcm/app/admin/models"
	"vrcm/src/vrcm/app/admin/service/dto/alert"
	"vrcm/src/vrcm/common/service"
	ext "vrcm/src/vrcm/envconfig"
)

var client = http.Client{}

type AlertService struct {
	service.Service
}

func (e AlertService) AlertInfo(info alert.WarnInfo) error {
	bytesData, _ := json.Marshal(info)
	e.Log.Trace("AlertInfo url:", string(bytesData))

	//resp, err := http.Post(ext.ExtConfig.ServiceConfig.AlertServiceUrl+"/v1/client/alerts", "application/json", bytes.NewReader(bytesData))
	req, err := http.NewRequest("POST", ext.ExtConfig.ServiceConfig.AlertServiceUrl+"/v1/client/alerts", bytes.NewReader(bytesData))
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+models.SuperToken)
	req.Header.Set("X-PS-Flag", "")
	req.Header.Set("Content-Type", "application/json")
	if err != nil {
		return err
	} else {
		req.Body.Close()
	}

	response, err := client.Do(req)
	if err != nil {
		e.Log.Error("GetHttpSkip Response Error:", err)
		return err
	}

	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		e.Log.Error("读取响应体失败 error:%s", err)
		return err
	}
	e.Log.Info("AlertInfo:", string(body))
	result := gjson.Parse(string(body))
	if result.Get("code").Int() != http.StatusOK {
		return errors.New(result.Get("message").String())
	}

	//e.Log.Trace("AlertInfo:", resp)
	return nil
}
